package com.xcx.robot.mirai.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xcx.robot.mirai.QuickStart;
import com.xcx.robot.mirai.config.UserConfig;
import com.xcx.robot.mirai.entity.ApiResult;
import com.xcx.robot.mirai.key.DrawImg;
import com.xcx.robot.util.DateUtils;
import com.xcx.robot.util.ImageUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import net.mamoe.mirai.contact.ContactList;
import net.mamoe.mirai.contact.Group;
import net.mamoe.mirai.message.data.PlainText;
import net.mamoe.mirai.utils.ExternalResource;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: 邢晨旭
 * @Date: 2021/6/16 14:00
 * @Description:
 */
@Slf4j
public class MyWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Resource
    UserConfig userConfig;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("与客户端建立连接，通道开启！");
        //添加到channelGroup通道组
        MyChannelHandlerPool.channelGroup.add(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("与客户端断开连接，通道关闭！");
        //添加到channelGroup 通道组
        MyChannelHandlerPool.channelGroup.remove(ctx.channel());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //首次连接是FullHttpRequest，处理参数 by zhengkai.blog.csdn.net
        if (null != msg && msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            String uri = request.uri();

            Map paramMap = getUrlParams(uri);
            log.info("接收到的参数是：" + JSON.toJSONString(paramMap));
            //如果url包含参数，需要处理
            if (uri.contains("?")) {
                String newUri = uri.substring(0, uri.indexOf("?"));
                System.out.println(newUri);
                request.setUri(newUri);
            }

        } else if (msg instanceof TextWebSocketFrame) {
            //正常的TEXT消息类型
            TextWebSocketFrame frame = (TextWebSocketFrame) msg;
            log.info("客户端收到服务器数据：" + frame.text());
//            test(frame.text());
            sendAllMessage(frame.text());
        }
        super.channelRead(ctx, msg);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {

    }

    private void sendAllMessage(String message) {
        //收到信息后，群发给所有channel
        MyChannelHandlerPool.channelGroup.writeAndFlush(new TextWebSocketFrame(message));
    }

    private static Map getUrlParams(String url) {
        Map<String, String> map = new HashMap<>();
        url = url.replace("?", ";");
        if (!url.contains(";")) {
            return map;
        }
        if (url.split(";").length > 0) {
            String[] arr = url.split(";")[1].split("&");
            for (String s : arr) {
                String key = s.split("=")[0];
                String value = s.split("=")[1];
                map.put(key, value);
            }
            return map;

        } else {
            return map;
        }
    }


    private void test(String msg) {
        try {
            ApiResult apiResult = JSONObject.parseObject(msg, ApiResult.class);
            ApiResult data = apiResult.getData();
            log.info("ApiResult:"+apiResult+"\ndata:"+data);
            ContactList<Group> groups = QuickStart.bot.getGroups();
            List<Group> groupCollect = new ArrayList<>(groups);
            //TODO 配置读取
            log.info("排除交互的群粗配置信息"+UserConfig.excludeGroups);
            groupCollect.removeIf(group -> UserConfig.excludeGroups.contains(group.getId()));
            StringBuilder result = new StringBuilder();
            ExternalResource image = null;
            switch (apiResult.getType()) {
                case "2001":
                    if ("1".equals(data.getStatus())) {
                        //剑胆琴心开服了{"type": 2001, "data": {"server": "剑胆琴心", "status": 1}}
                        image = ImageUtils.initImage(DrawImg.openServer("剑胆琴心"));
                        result.append("剑胆琴心开服了\n").append(DateUtils.getDateTime());
                        break;
                    }
                    if ("0".equals(data.getStatus())) {
                        //剑胆琴心开服了
                        result.append("剑胆琴心倒闭了\n").append(DateUtils.getDateTime());
                        break;
                    }
                    break;
                case "2002":
                    //新闻资讯"type": "官方新闻",
                    //    "title": "10000份测试资格明日发放 《剑网3》“白帝风云”三测将至",
                    //    "url": "https://jx3.xoyo.com/show-2458-4454-1.html",
                    //    "date": "04/11"
                    result.append(data.getTitle()).append("\n").append(data.getUrl()).append("\n").append(DateUtils.getDate());
                    break;
                case "2003":
                    //奇遇播报"server": "梦江南",
                    //    "name": "小慕玖",
                    //    "time": 1618123365,
                    //    "serendipity": "雪山恩仇"
                    result.append(DateUtils.getDateTime()).append(" ").append(data.getName()).append("触发了奇遇 ").append(data.getSerendipity())
                            .append("\n").append("让我们恭喜这个b");
                    break;
                default:
            }
            ExternalResource finalImage = image;
            groupCollect.forEach(group -> {
                if(finalImage !=null){
                    group.sendMessage(group.uploadImage(finalImage));
                }else{
                    group.sendMessage(result.toString());
                }

            });
        } catch (Exception e) {
            log.error("异常信息：",e);
        }


    }

    public static void main(String[] args) {
        String s = "{\"type\": 2001, \"data\": {\"server\": \"绝代天骄\", \"status\": 1}}";
    }

}
